#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#define SDL_DELAY 12

SDL_Window *window;
SDL_Renderer *render;
SDL_Event e;
int gQuit = 0;
Mix_Chunk *gameMusic;
int gMusicCondition = 1;
int init()
{
    int ret = 1;
      Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
  Mix_AllocateChannels(16);
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0)
    {
        printf("sdl could not init!sdl error:%s\n", SDL_GetError());
        ret = 0;
    }
    else
    {
        if ((window = SDL_CreateWindow("sdl", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 300, 0)) == NULL)
        {
            printf("could not create! error:%s\n", SDL_GetError());
            ret = 0;
        }
        else
        {
            if ((render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == NULL)
            {
                printf("render could not create! error:%s\n", SDL_GetError());
                ret = 0;
            }
        }
    }
    return ret;
}
void switchMusic() {
  gMusicCondition = !gMusicCondition;
}

Mix_Chunk *loadWAV(const char *filepath) {
  SDL_RWops *fileData = SDL_RWFromFile(filepath, "rb");
  if(!fileData) {
    printf("SDL_RWFromFile: %s\n", SDL_GetError());
    return NULL;
  }
  
  Mix_Chunk *chunk = Mix_LoadWAV_RW(fileData, 1);
  if(!chunk){
    printf("Mix_LoadWAV_RW: %s\n", Mix_GetError());
    SDL_FreeRW(fileData);
    return NULL;
  }
  
  return chunk;
}

void loadMedia(){
  gameMusic = loadWAV("bgm.ogg");

}
void playMusic() {
  if (gMusicCondition) {
    if (Mix_Paused(1)) {
      Mix_Resume(1);
    } else {
      Mix_PlayChannel(1, gameMusic, -1);
    }
  }
}

void handleButtons()
{
    switch (e.type)
    {
    case SDL_QUIT:
        gQuit = 1;
        break;
    case SDL_KEYDOWN:
        if (e.key.keysym.sym == 'q')
            gQuit = 1;
        else if(e.key.keysym.sym == 'm'){
            switchMusic();
        }else if(e.key.keysym.sym == 'p'){
            playMusic();
            
        }else if(e.key.keysym.sym == 's'){
            Mix_Pause(1);
        }
        break;
    }
}
void tick()
{
    SDL_RenderClear(render);

    while (SDL_PollEvent(&e) != 0)
    {
        handleButtons();
    }
    SDL_SetRenderDrawColor(render, 0, 0, 255, 255);
    SDL_RenderPresent(render);
}

void quit()
{
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

void loop()
{
    while (!gQuit)
    {
        SDL_Delay(SDL_DELAY);
        tick();
    }
    quit();
}
int main(int argc, char *argv[])
{
    if (!init())
    {
        printf("init error!\n");
    }
    else
    {
        loadMedia();
        loop();
    }
    return 0;
}